import { Controller } from 'egg';

class ProjectController extends Controller {
  // 获取项目列表
  async list() {
    const { ctx } = this;
    const { page = 1, pageSize = 10, category, status, keyword } = ctx.query;

    try {
      const where: any = {};
      
      if (category) {
        where.category = category;
      }
      
      if (status) {
        where.status = status;
      }
      
      if (keyword) {
        where[ctx.app.Sequelize.Op.or] = [
          { title: { [ctx.app.Sequelize.Op.like]: `%${keyword}%` } },
          { description: { [ctx.app.Sequelize.Op.like]: `%${keyword}%` } }
        ];
      }

      const { count, rows } = await ctx.model.Project.findAndCountAll({
        where,
        include: [
          {
            model: ctx.model.User,
            as: 'creator',
            attributes: ['id', 'name', 'avatar']
          }
        ],
        limit: parseInt(String(pageSize)),
        offset: (parseInt(String(page)) - 1) * parseInt(String(pageSize)),
        order: [['createdAt', 'DESC']]
      });

      ctx.body = {
        success: true,
        data: {
          list: rows,
          pagination: {
            page: parseInt(String(page)),
            pageSize: parseInt(String(pageSize)),
            total: count
          }
        }
      };
    } catch (error) {
      ctx.logger.error('获取项目列表失败:', error);
      ctx.status = 500;
      ctx.body = { success: false, message: '获取项目列表失败' };
    }
  }

  // 获取项目详情
  async detail() {
    const { ctx } = this;
    const { id } = ctx.params;

    try {
      const project = await ctx.model.Project.findByPk(id, {
        include: [
          {
            model: ctx.model.User,
            as: 'creator',
            attributes: ['id', 'name', 'avatar', 'bio']
          },
          {
            model: ctx.model.Donation,
            as: 'donations',
            include: [
              {
                model: ctx.model.User,
                as: 'donor',
                attributes: ['id', 'name', 'avatar']
              }
            ],
            order: [['createdAt', 'DESC']]
          },
          {
            model: ctx.model.ProjectUpdate,
            as: 'updates',
            include: [
              {
                model: ctx.model.User,
                as: 'author',
                attributes: ['id', 'name', 'avatar']
              }
            ],
            order: [['createdAt', 'DESC']]
          }
        ]
      });

      if (!project) {
        ctx.status = 404;
        ctx.body = { success: false, message: '项目不存在' };
        return;
      }

      ctx.body = {
        success: true,
        data: project
      };
    } catch (error) {
      ctx.logger.error('获取项目详情失败:', error);
      ctx.status = 500;
      ctx.body = { success: false, message: '获取项目详情失败' };
    }
  }

  // 创建项目
  async create() {
    const { ctx } = this;
    const { title, description, content, category, targetAmount, endDate, images, documents } = ctx.request.body;

    try {
      const userId = ctx.state.user.userId;

      const project = await ctx.model.Project.create({
        title,
        description,
        content,
        category,
        targetAmount: parseFloat(targetAmount),
        endDate: new Date(endDate),
        images: images ? JSON.stringify(images) : null,
        documents: documents ? JSON.stringify(documents) : null,
        creatorId: userId,
        status: 'pending'
      });

      ctx.body = {
        success: true,
        message: '项目创建成功',
        data: project
      };
    } catch (error) {
      ctx.logger.error('创建项目失败:', error);
      ctx.status = 500;
      ctx.body = { success: false, message: '创建项目失败' };
    }
  }

  // 更新项目
  async update() {
    const { ctx } = this;
    const { id } = ctx.params;
    const updateData = ctx.request.body;

    try {
      const project = await ctx.model.Project.findByPk(id);
      
      if (!project) {
        ctx.status = 404;
        ctx.body = { success: false, message: '项目不存在' };
        return;
      }

      // 检查权限
      if (project.creatorId !== ctx.state.user.userId && ctx.state.user.role !== 'admin') {
        ctx.status = 403;
        ctx.body = { success: false, message: '无权限修改此项目' };
        return;
      }

      await project.update(updateData);

      ctx.body = {
        success: true,
        message: '项目更新成功',
        data: project
      };
    } catch (error) {
      ctx.logger.error('更新项目失败:', error);
      ctx.status = 500;
      ctx.body = { success: false, message: '更新项目失败' };
    }
  }

  // 删除项目
  async delete() {
    const { ctx } = this;
    const { id } = ctx.params;

    try {
      const project = await ctx.model.Project.findByPk(id);
      
      if (!project) {
        ctx.status = 404;
        ctx.body = { success: false, message: '项目不存在' };
        return;
      }

      // 检查权限
      if (project.creatorId !== ctx.state.user.userId && ctx.state.user.role !== 'admin') {
        ctx.status = 403;
        ctx.body = { success: false, message: '无权限删除此项目' };
        return;
      }

      await project.destroy();

      ctx.body = {
        success: true,
        message: '项目删除成功'
      };
    } catch (error) {
      ctx.logger.error('删除项目失败:', error);
      ctx.status = 500;
      ctx.body = { success: false, message: '删除项目失败' };
    }
  }

  // 批准项目
  async approve() {
    const { ctx } = this;
    const { id } = ctx.params;

    try {
      // 检查管理员权限
      if (ctx.state.user.role !== 'admin') {
        ctx.status = 403;
        ctx.body = { success: false, message: '无权限操作' };
        return;
      }

      const project = await ctx.model.Project.findByPk(id);
      
      if (!project) {
        ctx.status = 404;
        ctx.body = { success: false, message: '项目不存在' };
        return;
      }

      await project.update({
        status: 'approved',
        approvedAt: new Date(),
        approvedBy: ctx.state.user.userId
      });

      ctx.body = {
        success: true,
        message: '项目批准成功'
      };
    } catch (error) {
      ctx.logger.error('批准项目失败:', error);
      ctx.status = 500;
      ctx.body = { success: false, message: '批准项目失败' };
    }
  }

  // 拒绝项目
  async reject() {
    const { ctx } = this;
    const { id } = ctx.params;
    const { reason } = ctx.request.body;

    try {
      // 检查管理员权限
      if (ctx.state.user.role !== 'admin') {
        ctx.status = 403;
        ctx.body = { success: false, message: '无权限操作' };
        return;
      }

      const project = await ctx.model.Project.findByPk(id);
      
      if (!project) {
        ctx.status = 404;
        ctx.body = { success: false, message: '项目不存在' };
        return;
      }

      await project.update({
        status: 'rejected',
        rejectReason: reason,
        approvedBy: ctx.state.user.userId
      });

      ctx.body = {
        success: true,
        message: '项目拒绝成功'
      };
    } catch (error) {
      ctx.logger.error('拒绝项目失败:', error);
      ctx.status = 500;
      ctx.body = { success: false, message: '拒绝项目失败' };
    }
  }
}

export default ProjectController;
